package com.colin.log.feign;

import com.colin.log.util.IdUtil;
import com.colin.log.util.IpUtil;
import com.colin.log.util.LogUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.MDC;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * feign请求日志配置
 */
public class FeignLogInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        
        if(attributes != null){
            HttpServletRequest request = attributes.getRequest();
            
            String traceId = MDC.get(LogUtil.LOG_PARAM_TRACE_ID);
            if (traceId == null || traceId.length() == 0) {
                traceId = IdUtil.getUUID();
            }
            MDC.put(LogUtil.LOG_PARAM_CLIENT_IP, IpUtil.getClientIp(request));
            requestTemplate.header(LogUtil.LOG_PARAM_TRACE_ID, traceId);
        }
    }
}
